package org.jeecg.modules.pos.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.*;
import org.jeecg.modules.kc.service.IKcDepositoryInGoodsService;
import org.jeecg.modules.pos.dto.OrderPaymentDto;
import org.jeecg.modules.pos.entity.PosOrderGoods;
import org.jeecg.modules.pos.entity.PosOrderGoodsPayment;
import org.jeecg.modules.pos.entity.PosTable;
import org.jeecg.modules.pos.service.IPosOrderGoodsDetailService;
import org.jeecg.modules.pos.service.IPosOrderGoodsPaymentService;
import org.jeecg.modules.pos.service.IPosOrderGoodsService;
import org.jeecg.modules.pos.service.IPosTableService;
import org.jeecg.modules.rooms.service.CesGoodsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

 /**
 * @Description: pos_order_goods_payment
 * @Author: jeecg-boot
 * @Date:   2023-04-13
 * @Version: V1.0
 */
@Api(tags="pos_order_goods_payment")
@RestController
@RequestMapping("/pos/posOrderGoodsPayment")
@Slf4j
public class PosOrderGoodsPaymentController extends JeecgController<PosOrderGoodsPayment, IPosOrderGoodsPaymentService> {
	@Autowired
	private IPosOrderGoodsPaymentService posOrderGoodsPaymentService;
	 @Autowired
	 private IPosOrderGoodsService posOrderGoodsService;
	 @Autowired
	 private IBusRoomPayTypeService busRoomPayTypeService;
	 @Autowired
	 private IPosTableService posTableService;
	 @Resource
	 private IPosOrderGoodsDetailService posOrderGoodsDetailService;
	 @Resource
	 private CesGoodsServiceImpl goodsService;
	 @Resource
	 private IBusRoomPayTypeService payTypeService;
	 @Resource
	 IBusMemberCardService memberCardService;
	 @Resource
	 IBusMemberBalanceLogService memberBalanceLogService;
	 @Resource
	 IBusMarketAgreementUnitService marketAgreementUnitService;
	 @Resource
	 IBusAgreementOrderFeeService agreementOrderFeeService;

	 @Resource
	 private IKcDepositoryInGoodsService depositoryInGoodsService;
	/**
	 * 分页列表查询
	 *
	 * @param posOrderGoodsPayment
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "pos_order_goods_payment-分页列表查询")
	@ApiOperation(value="pos_order_goods_payment-分页列表查询", notes="pos_order_goods_payment-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<PosOrderGoodsPayment>> queryPageList(PosOrderGoodsPayment posOrderGoodsPayment,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PosOrderGoodsPayment> queryWrapper = QueryGenerator.initQueryWrapper(posOrderGoodsPayment, req.getParameterMap());
		Page<PosOrderGoodsPayment> page = new Page<PosOrderGoodsPayment>(pageNo, pageSize);
		IPage<PosOrderGoodsPayment> pageList = posOrderGoodsPaymentService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "pos_order_goods_payment-添加")
	@ApiOperation(value="pos_order_goods_payment-添加", notes="pos_order_goods_payment-添加")
	//@RequiresPermissions("pos:pos_order_goods_payment:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody OrderPaymentDto dto,String hotel) {
		if (ObjectUtils.isEmpty(dto.getPaymentList())) {
			return Result.error("请先选择支付方式");
		}
		LambdaQueryWrapper<PosOrderGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(PosOrderGoods::getCode, dto.getOrderCode());
		PosOrderGoods posOrderGoods = posOrderGoodsService.getOne(lambdaQueryWrapper);
		if (ObjectUtils.isEmpty(posOrderGoods)) {
			return Result.error("订单不存在");
		}
		BigDecimal sum = BigDecimal.ZERO;
		String payInfo = "";
		for (PosOrderGoodsPayment posOrderGoodsPayment : dto.getPaymentList()) {
			posOrderGoodsPayment.setTenantId(posOrderGoods.getTenantId());
			posOrderGoodsPayment.setHotelId(posOrderGoods.getHotelId());
			sum = sum.add(posOrderGoodsPayment.getPayMoney());
			BusRoomPayType busRoomPayType = busRoomPayTypeService.getById(posOrderGoodsPayment.getPaymentMethod());
			if (busRoomPayType != null) {
				payInfo += busRoomPayType.getName() + String.format("%.2f", posOrderGoodsPayment.getPayMoney());
			}
		}
		posOrderGoodsPaymentService.saveBatch(dto.getPaymentList());
		// 有会员卡支付的费用时
		List<BusRoomPayType> payTypeList = payTypeService.list();
		payTypeList.stream().filter(e -> "会员卡".equals(e.getName())).findFirst().ifPresent(type -> {
			//找出会员支付的账单
			List<PosOrderGoodsPayment> goodsPaymentList = dto.getPaymentList().stream().filter(payment -> type.getId().equals(payment.getPaymentMethod())).collect(Collectors.toList());
			if (CollUtil.isNotEmpty(goodsPaymentList) && StrUtil.isNotEmpty(dto.getCardId())) {
				BusMemberCard card = memberCardService.getById(dto.getCardId());
				if (card == null) {
					throw new JeecgBootException("未找到会员卡");
				}
				ArrayList<BusMemberBalanceLog> memberBalanceLogList = new ArrayList<>();
				goodsPaymentList.forEach(payment -> {
					BusMemberBalanceLog memberBalanceLog = memberCardService.cardPayFee(card, payment.getPayMoney(), payment.getId(), hotel);
					memberBalanceLogList.add(memberBalanceLog);
				});
				memberCardService.updateById(card);
				memberBalanceLogService.saveBatch(memberBalanceLogList);
			}
		});
		// 有单位挂账的费用时
		payTypeList.stream().filter(e -> "单位挂账".equals(e.getName())).findFirst().ifPresent(type -> {
			//找出会员支付的账单
			List<PosOrderGoodsPayment> goodsPaymentList = dto.getPaymentList().stream().filter(payment -> type.getId().equals(payment.getPaymentMethod())).collect(Collectors.toList());
			if (CollUtil.isNotEmpty(goodsPaymentList) && StrUtil.isNotEmpty(dto.getAgreementId())) {
				BusMarketAgreementUnit agreementUnit = marketAgreementUnitService.getById(dto.getAgreementId());
				if (agreementUnit == null) {
					throw new JeecgBootException("未找到合同单位");
				}
				ArrayList<BusAgreementOrderFee> memberBalanceLogList = new ArrayList<>();
				goodsPaymentList.forEach(payment -> {
					BusAgreementOrderFee agreementOrderFee = marketAgreementUnitService.agreementPayFee(agreementUnit, payment.getPayMoney(), payment.getId(), hotel);
					memberBalanceLogList.add(agreementOrderFee);
				});
				marketAgreementUnitService.updateById(agreementUnit);
				agreementOrderFeeService.saveBatch(memberBalanceLogList);
			}
		});
		posOrderGoods.setSettleTime(new Date());
		posOrderGoods.setStatus(1);
		posOrderGoods.setPayMoney(sum);
		posOrderGoods.setCouponMoney(posOrderGoods.getConsumeMoney().subtract(sum));
		posOrderGoods.setPayInfo(payInfo);
		posOrderGoodsService.updateById(posOrderGoods);
		// 桌台下单情况下,修改桌台状态
		if (ObjectUtils.isNotEmpty(posOrderGoods.getPosTableId())) {
			LambdaUpdateWrapper<PosTable> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
			lambdaUpdateWrapper.eq(PosTable::getId, posOrderGoods.getPosTableId());
			lambdaUpdateWrapper.set(PosTable::getState, 4);
			posTableService.update(lambdaUpdateWrapper);
		}
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param posOrderGoodsPayment
	 * @return
	 */
	@AutoLog(value = "pos_order_goods_payment-编辑")
	@ApiOperation(value="pos_order_goods_payment-编辑", notes="pos_order_goods_payment-编辑")
	//@RequiresPermissions("pos:pos_order_goods_payment:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody PosOrderGoodsPayment posOrderGoodsPayment) {
		posOrderGoodsPaymentService.updateById(posOrderGoodsPayment);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "pos_order_goods_payment-通过id删除")
	@ApiOperation(value="pos_order_goods_payment-通过id删除", notes="pos_order_goods_payment-通过id删除")
	//@RequiresPermissions("pos:pos_order_goods_payment:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		posOrderGoodsPaymentService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "pos_order_goods_payment-批量删除")
	@ApiOperation(value="pos_order_goods_payment-批量删除", notes="pos_order_goods_payment-批量删除")
	//@RequiresPermissions("pos:pos_order_goods_payment:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.posOrderGoodsPaymentService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "pos_order_goods_payment-通过id查询")
	@ApiOperation(value="pos_order_goods_payment-通过id查询", notes="pos_order_goods_payment-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<PosOrderGoodsPayment> queryById(@RequestParam(name="id",required=true) String id) {
		PosOrderGoodsPayment posOrderGoodsPayment = posOrderGoodsPaymentService.getById(id);
		if(posOrderGoodsPayment==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(posOrderGoodsPayment);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param posOrderGoodsPayment
    */
    //@RequiresPermissions("pos:pos_order_goods_payment:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PosOrderGoodsPayment posOrderGoodsPayment) {
        return super.exportXls(request, posOrderGoodsPayment, PosOrderGoodsPayment.class, "pos_order_goods_payment");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("pos:pos_order_goods_payment:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PosOrderGoodsPayment.class);
    }

}
